package com.liu.web.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author LIU
 * @version 1.0
 * @description: TODO
 * @date 2023/6/5 16:43
 */
@Slf4j
public class MyServlet extends HttpServlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        // 第一次调用时初始化。
        log.info("MyServlet init 方法执行了");
        super.init(servletConfig);
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse response) throws ServletException, IOException {
        log.info("MyServlet services 方法执行了");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        ServletInputStream inputStream = request.getInputStream();

        int ch=0;
        //每次读取一个字符
        while((ch=inputStream.read())!=-1){
            System.out.print((char)ch);
        }
        System.out.println();

        // 设置HttpServletResponse使用UTF-8编码
//        response.setCharacterEncoding("utf-8");
        // 通知浏览器使用utf-8解码
        response.setContentType("text/html; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("MyServlet访问成功");
        writer.close();
    }

}
